import React from 'react';
import {connect} from 'react-redux';
import constants from 'share/constants';
import {Form, Select, Button, message, Switch, Radio, Row, Col, Checkbox} from 'antd'
import LanguageInput from 'components/template/language-input/language-input'
import Chooser from 'components/chooser'
const FormItem = Form.Item;
const Option = Select.Option;
const RadioGroup = Radio.Group;
import 'styles/pay-setting/payment-method/new-payment-method.scss'
import {messages} from 'share/common'
import  EmailNotificationService from 'containers/setting/email-notification/email-notification.service'
/**请查看*注：请根据公司政策考虑是否需要打印*/
const defaultContent = `${messages('setting.key491'/*，请查看。*/)}\r\n${messages('setting.key492'/*注：请根据公司政策考虑是否打印。*/)}\r\n${"www.huilianyi.com"}`;
const defaultTitle = `${messages('setting.key493'/*单据名称*/)}${messages('setting.key494'/*打印*/)}`;
class NewEmailNotification extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      params: {},
      loading: false,
      newSheet: {
        i18n: {},
        title: defaultTitle,
        content: defaultContent,
        visibleCompanyScope: 1,
        contentHead:true,
      },
      value: true,
      checked: true,
      name: '',
      nameI18n: [],
      saveParam: {
        i18n: {},
        title: defaultTitle,
        content: defaultContent,
        visibleCompanyScope: 1,
        contentHead:true,
      },
      contentInRule:[],
      titleInRule:[],
    };
  }

  componentWillMount() {
    let params = this.props.params;
    const {languageList} = this.props;
    languageList.map(language => {
      if (language.code.toLowerCase() === this.props.language.code.toLowerCase()) {
        this.state.contentInRule.push({
          language: language.code.toLowerCase(),
          length: 500,
        });
        this.state.titleInRule.push({
          language: language.code.toLowerCase(),
          length: 100,
        });
      }
    })
    if (params && JSON.stringify(params) != "{}") {
      this.setState({
        newSheet: params,
        saveParam: JSON.parse(JSON.stringify(params))
      })
    }

  }


  handleSave = (e) => {
    e.preventDefault();
    const {newSheet} = this.state;
    this.props.form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        let account = Object.assign({}, newSheet, values);
        if (JSON.stringify(this.props.params) === "{}") {
          this.newAccount(account);
        } else {
          this.editAccount(account);
        }
      }
    });
  };

  //新增
  newAccount = (account) => {
    let _this = this;
    if (account.title === '') {
      message.error(`${messages('common.please.enter')}${messages('setting.key495'/*邮件标题*/)}`)
      return;
    } else if (account.content === '') {
      message.error(`${messages('common.please.enter')}${messages('setting.key496'/*邮件正文*/)}`)
      return;
    }
    account.companyOIDList = this.state.newSheet.companyOIDList;
    account.visibleCompanyScope = this.state.newSheet.visibleCompanyScope;
    if( account.visibleCompanyScope === 2 &&
      (this.state.newSheet.customCompanyRelationResps === undefined ||
      (this.state.newSheet.customCompanyRelationResps && this.state.newSheet.customCompanyRelationResps.length == 0))) {
      message.error(`${messages('common.please.select')}${messages('setting.key837'/*公司*/)}`)
      return;
    }
    if(account.visibleCompanyScope === 1 ){
      account.customCompanyRelationResps = [];
      account.companyOIDList =[];
    }
    this.setState({loading: true});
    let newSheet = {
      i18n: {},
      title: defaultTitle,
      content: defaultContent,
      visibleCompanyScope: 1,
      contentHead: true,
    }
    EmailNotificationService.addOrUpdateMailTemplate(account)
      .then((res) => {
        _this.setState({
          newSheet,
          loading: false,
        }, ()=>{
          _this.props.form.resetFields();
          _this.props.close(true);
        });
        message.success(messages("common.save.success", { name: "" }));
      })
  }
  //修改
  editAccount = (account) => {
    let _this = this;
    if (account.title === '') {
      message.error(`${messages('common.please.enter')}${messages('setting.key495'/*邮件标题*/)}`)
      return;
    } else if (account.content === '') {
      message.error(`${messages('common.please.enter')}${messages('setting.key496'/*邮件正文*/)}`)
      return;
    }
    account.companyOIDList = this.state.newSheet.companyOIDList;
    account.visibleCompanyScope = this.state.newSheet.visibleCompanyScope;
    if( account.visibleCompanyScope === 2 &&
      (this.state.newSheet.customCompanyRelationResps === undefined||
      (this.state.newSheet.customCompanyRelationResps&&this.state.newSheet.customCompanyRelationResps.length==0))){
      message.error(`${messages('common.please.select')}${messages('setting.key837'/*公司*/)}`)
      return;
    }
    if(account.visibleCompanyScope === 1 ){
      account.customCompanyRelationResps = [];
      account.companyOIDList =[];
    }
    this.setState({loading: true});
    EmailNotificationService.addOrUpdateMailTemplate(account)
      .then((res) => {
        _this.setState({
          newSheet: account,
          loading: false,
        }, function () {
          _this.props.form.resetFields();
          _this.props.close(true);
        });
        message.success(messages("common.save.success", { name: "" }));
      })

  }

  onCancel = () => {
    this.setState({
      newSheet: this.state.saveParam,
    }, function () {
      this.props.form.resetFields();
      this.props.close();
    })
  };

  handleNewSheetChange = (value, i18n) => {
    let newSheet = this.state.newSheet;
    newSheet.title = value;
    newSheet.i18n.title = i18n;
    this.setState({newSheet})
  }

  handleNewSheetContentChange = (value, i18n) => {
    let newSheet = this.state.newSheet;
    newSheet.content = value;
    newSheet.i18n.content = i18n;
    this.setState({newSheet})
  };

  //切换选项
  onChange = (e) => {
    console.log('radio checked', e.target.value);
    this.setState({
      value: e.target.value,
    });
  };

  onChangeCheckBox = (e) => {
    let newSheet = this.state.newSheet;
    newSheet.contentHead = e.target.checked
    this.setState({
      newSheet
    });
  };

  formChange = () => {
    this.setState({
      loading: false,
    });
  };

  handleChangeFormType = (e) => {
    let newSheet = this.state.newSheet;
    const {languageList} = this.props;
    constants.printDocumentType.map((item) => {
      if (item.value === e) {
        newSheet.formTypeDesc = item.text;
        newSheet.title = `${newSheet.formTypeDesc}${messages('common.print')}`;
        newSheet.i18n.title = [];
        languageList.map(language => {
          if (language.code.toLowerCase() === this.props.language.code.toLowerCase()) {
            newSheet.i18n.title.push({
              language: language.code.toLowerCase(),
              value: `${newSheet.formTypeDesc}${messages('common.print')}`
            })
          }
        })
        this.setState({newSheet});
      }
    })
  };

  handleChangeCompany = (e) => {
    let newSheet = this.state.newSheet;
    newSheet.visibleCompanyScope = e.target.value;
    this.setState({
      newSheet
    });
  };
  handleSelectCompany = (value) => {
    let newSheet = this.state.newSheet;
    let companyArr = [];
    let companyValue = []
    value.forEach(item => {
      companyArr.push(item.companyOID);
      companyValue.push(item);
    });
    newSheet.companyOIDList = companyArr;
    newSheet.customCompanyRelationResps = companyValue;
    this.setState({
      newSheet
    });
  };

  render() {
    const {getFieldDecorator} = this.props.form;
    const {newSheet, loading, titleInRule, contentInRule} = this.state;
    const {tenantMode, params} = this.props;
    const formItemLayout = {
      labelCol: {span: 6},
      wrapperCol: {span: 14, offset: 1},
    };
    const defaultPreview = `${'Hi,'}${messages('setting.key497'/*附件是*/)}${ messages('setting.key498'/*您于*/)}${ messages('setting.key499'/*单据提交时间*/)}${ messages('setting.key500'/*提交的*/)}`;
    const defaultCheckboxText =
      <span>Hi，{messages('setting.key497'/*附件是*/)}{messages('setting.key498'/*您于*/)}<span
        className='default-color-font'>&nbsp;{messages('setting.key499'/*单据提交时间*/)}</span>
        {messages('setting.key500'/*提交的*/)}</span>
    const formItemNoLabel = {
      wrapperCol: {span: 14, offset: 7},
    };
    return (
      <div className="new-payment-method">
        <Form onSubmit={this.handleSave}>
          <FormItem {...formItemLayout} label={messages('common.column.status'/*状态*/)}>
            {getFieldDecorator('valid', {
              initialValue: params.id ? params.valid : true
            })(
              <Switch disabled={!tenantMode} checked={this.props.form.getFieldValue('valid')}/>
            )}
          </FormItem>
          <FormItem {...formItemLayout} label={messages('setting.key84'/*适用单据*/)}>
            {getFieldDecorator('formTypeId', {
              rules: [{
                required: true,
                message: messages('common.please.select')
              }],
              initialValue: params.formTypeId ? params.formTypeId : ''
            })(
              <Select disabled={!tenantMode} placeholder={messages('common.please.select')}
                      onChange={this.handleChangeFormType}>
                {
                  constants.printDocumentType.map((item) => <Option key={item.value}
                                                                    value={item.value}>{item.text}</Option>)
                }
              </Select>
            )}
          </FormItem>
          <Row type="flex" align="middle" style={{marginBottom: '25px'}}>
            <Col span={6}
                 className='font-title'
                 style={{fontSize: '14px', textAlign: 'right', alignSelf: 'stretch'}}>
              {messages('setting.key486'/*适用公司*/)}：
            </Col>
            <Col span={14} offset={1}>
              <RadioGroup disabled={!tenantMode} onChange={this.handleChangeCompany}
                          value={newSheet.visibleCompanyScope}>
                <Radio value={1}>{messages('common.all')/*全部*/}</Radio>
                <Radio value={2}>{messages('setting.key501'/*部分*/)}</Radio>
              </RadioGroup>
              {newSheet.visibleCompanyScope === 2 &&
              <div style={{marginTop: '30px'}}>
                <Chooser style={{marginTop: '30px'}} placeholder={messages('common.please.select')}
                         type='available_company'
                         labelKey='name'
                         disabled={!tenantMode}
                         valueKey='companyOID'
                         onChange={this.handleSelectCompany}
                         value={newSheet.customCompanyRelationResps}
                         single={false}/>

              </div>
              }
            </Col>
          </Row>
          <Row type="flex" align="middle" style={{marginBottom: '25px'}}>
            <Col span={6} className='font-title' style={{fontSize: '14px', textAlign: 'right'}}>
              <span className='default-color-inverse-font'>*</span>{messages('setting.key495'/*邮件标题*/)}：
            </Col>
            <Col span={14} offset={1}>
              <LanguageInput
                disabled={!tenantMode}
                name={newSheet.title}
                value={newSheet.title}
                inpRule={titleInRule}
                isEdit
                i18nName={newSheet.i18n.title}
                nameChange={(value, i18n) => this.handleNewSheetChange(value, i18n)}/>
            </Col>
          </Row>
          <Row type="flex" align="middle" style={{marginBottom: '25px'}}>
            <Col span={6} className='font-title' style={{fontSize: '14px', textAlign: 'right'}}>
              <span className='default-color-inverse-font'>*</span>{messages('setting.key496'/*邮件正文*/)}：
            </Col>
            <Col span={14} offset={1}>
              <Checkbox disabled={!tenantMode}
                        defaultChecked={params.id ? params.contentHead: true}
                        onChange={this.onChangeCheckBox}>{defaultCheckboxText}
                <span className='default-color-font'>&nbsp;
                  {newSheet.formTypeDesc ? newSheet.formTypeDesc : messages('setting.key493'/*单据名称*/)}
                </span>
              </Checkbox>
            </Col>
          </Row>
          <FormItem {...formItemNoLabel}>
            <LanguageInput
              disabled={!tenantMode}
              isEdit
              inpRule={contentInRule}
              value={newSheet.content}
              name={newSheet.content}
              i18nName={newSheet.i18n.content ? newSheet.i18n.content : null}
              nameChange={(value, i18n) => this.handleNewSheetContentChange(value, i18n)}
              textArea={true}
            />
          </FormItem>
          <Row style={{marginBottom: '30px'}}>
            <Col span={14} offset={7}>
              <div>{messages('setting.key502'/*正文预览*/)}：</div>
              <div>
                <div style={{ whiteSpace: 'pre-wrap' }}>
                  {
                    this.state.checked ?
                      `${defaultPreview}${(newSheet.formTypeDesc ? newSheet.formTypeDesc :
                        messages('setting.key493'/*单据名称*/))}${newSheet.content}` : newSheet.content}
                </div>
              </div>
            </Col>
          </Row>
          {tenantMode && <div className="slide-footer">
            <Button type="primary"
                    htmlType="submit"
                    loading={loading}>{messages("common.save")}</Button>
            <Button onClick={this.onCancel}>{messages("common.cancel")}</Button>
          </div>}
        </Form>
      </div>
    )
  }
}


const WrappedNewEmailNotification = Form.create()(NewEmailNotification);

function mapStateToProps(state) {
  return {
    company: state.login.company,
    language: state.main.language,
    languageList: state.login.languageList,
    tenantMode: state.main.tenantMode,
  }
}
export default connect(mapStateToProps)(WrappedNewEmailNotification);
